<!--
 * @Description: 添加/展示/编辑消息模板的弹窗
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-11-02 17:15:31
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-13 15:49:17
-->

<template>
  <div class="dialog-for-column">
    <fks-dialog
      v-if="Visible"
      :class="operateType == 'show' ? 'view' : ''"
      :visible.sync="Visible"
      :append-to-body="true"
      width="480px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i :class="iconClass" />
        <span>{{ DialogTitle }}</span>
      </template>

      <div class="column-edit">
        <fks-form
          ref="Form"
          v-loading="loading"
          :model="Form"
          :disabled="operateType == 'show'"
          :rules="rules"
        >
          <fks-form-item
            :span="24"
            :label="LANG.TEMPLATE_NAME"
            prop="templateName"
          >
            <fks-input
              v-model="Form.templateName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            :span="24"
            :label="LANG.MSG_SEND_TYPE"
            prop="supportedMsgSendTypes"
          >
            <fks-select
              v-model="Form.supportedMsgSendTypes"
              style="width: 100%;"
              disabled
            >
              <fks-option
                v-for="item in msgSendTypeList"
                :key="item.code"
                :value="item.code"
                :label="item[$lang]"
              />
            </fks-select>
          </fks-form-item>

          <fks-form-item
            :span="24"
            :label="LANG.SERVICE_NAME"
            prop="serverId"
          >
            <fks-select
              v-model="Form.serverId"
              style="width: 100%;"
            >
              <fks-option
                v-for="item in serverList"
                :key="item.id"
                :value="item.id"
                :label="item.serverName ? item.serverName : item.id"
              />
            </fks-select>
          </fks-form-item>

          <fks-form-item
            :span="24"
            :label="LANG.THIRD_TEMPLATE_ID"
            prop="serverTemplateId"
          >
            <fks-input
              v-model="Form.serverTemplateId"
              maxlength="50"
              :placeholder="LANG.THIRD_TEMPLATE_ID_TIP"
            />
          </fks-form-item>
        </fks-form>
      </div>
      <!-- 提交按钮 -->
      <template slot="footer">
        <fks-button
          v-show="operateType != 'show' && !loading"
          type="primary"
          icon="fks-icon-check"
          @click="submit"
        >
          {{ LANG.SAVE }}
        </fks-button>
      </template>
    </fks-dialog>
  </div>
</template>

<script>
import { addTemplate } from '../../api'
import { ENUM } from '@/store/State/stateTypes'
import { getMsgTemplateById } from '../..//api'
export default {
  name: 'Sms',
  components: {},
  props: {
    visible: {
      type: Boolean
    },
    operateType: {
      type: String,
      default: 'new'
    },
    templateId: {
      type: String
    },
    msgSendType: {
      type: String
    },
    serverList: {
      type: Array,
      default: new Array()
    }
  },
  data() {
    return {
      Visible: false,
      loading: true,
      Form: {},
      defaultParams: [],
      paramsList: [],
      rules: {
        templateName: [{ required: true }],
        serverId: [{ required: true }],
        serverTemplateId: [{ required: true }]
      }
    }
  },
  computed: {
    DialogTitle() {
      if (this.operateType == 'new') return this.LANG.ADD
      if (this.operateType == 'edit') return this.LANG.EDIT
      return this.LANG.VIEW
    },
    msgSendTypeList() {
      return this.$store.state[ENUM].msgSendType || []
    },
    iconClass() {
      if (this.operateType == 'new') return 'fks-icon-plus'
      if (this.operateType == 'edit') return 'fks-icon-edit'
      return 'fks-icon-view'
    }
  },

  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.resetData()
        this.initData()
      }
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 将form处理为与接口对应的形式
     * @param {Object} form 表单的form
     * @return {Object} newForm 用于提交的form
     */
    dealForSubmit(form) {
      let newForm = JSON.parse(JSON.stringify(form))
      let arr = ['serverId', 'serverTemplateId']
      let obj = {
        serverId: newForm.serverId,
        serverTemplateId: newForm.serverTemplateId
      }
      newForm.templateParamList = arr.join()
      newForm.templateParamDefaultValue = JSON.stringify(obj)
      return newForm
    },

    submit() {
      this.$refs['Form'].validate((valid) => {
        if (valid) {
          this.submitForm()
        }
        if (!valid) {
          this.$message({
            type: 'error',
            message: this.LANG.ERROR_UNDO
          })
          return
        }
      })
    },

    submitForm: async function () {
      let submitForm = this.dealForSubmit(this.Form)
      addTemplate(submitForm, this.operateType).then((res) => {
        if (res.status) {
          this.$message({
            type: 'success',
            message:
              this.operateType == 'new'
                ? this.LANG.ADD_SUCCESS
                : this.LANG.EDIT_SUCCESS
          })
          this.$emit('submit')
        }
      })
    },

    /**
     * @description: 初始化Dialog
     *
     */
    initData: async function () {
      this.loading = true
      this.resetData()

      if (this.operateType == 'new') {
        this.Form = {
          supportedMsgSendTypes: this.msgSendType
        }
        this.loading = false
      }

      if (this.operateType == 'edit' || this.operateType == 'show') {
        getMsgTemplateById(this.templateId)
          .then((res) => {
            if (res.status) {
              let templateInfo = res.data
              this.Form = { ...templateInfo }
              if (templateInfo.templateParamDefaultValue) {
                let paramsValueList = JSON.parse(
                  templateInfo.templateParamDefaultValue
                )
                if (paramsValueList['serverId']) {
                  this.$set(this.Form, 'serverId', paramsValueList['serverId'])
                }
                if (paramsValueList['serverTemplateId']) {
                  this.$set(
                    this.Form,
                    'serverTemplateId',
                    paramsValueList['serverTemplateId']
                  )
                }
              }
            }
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      }
    },

    resetData() {
      this.Form = {}
    },

    cancel() {
      this.close()
    },

    close() {
      this.$emit('close')
      this.resetData()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
</style>
